import { Inject, Provide } from '@midwayjs/core';
import { InjectClient } from '@midwayjs/core';
import { query, transaction } from '../dbConnPool/mariadb'; // 引入查询函数
import { LoginDTO, UserDTO } from '../dto/user';
import { UserDao } from './userDao';
import { uuidv7 } from 'uuidv7';
import { CachingFactory, MidwayCache } from '@midwayjs/cache-manager';
//import { Caching} from "@midwayjs/cache-manager";

@Provide()
export class AuthDao {
  @Inject()
  userDao: UserDao;
  // 新注册用户
  async register(
    account: UserDTO['account'],
    name: UserDTO['name'],
    identity: UserDTO['identity'],
    sex: UserDTO['sex'],
    phone: UserDTO['phone'],
    email: UserDTO['email'],
    hashPassword: UserDTO['hashPassword']
  ) {
    const userId = uuidv7();
    return transaction(async conn => {
      const sql = `
        INSERT INTO user
          ( user_id, account, name, identity, sex, phone, email, password, created_at)
          VALUES ( ?,?, ?, ?, ?, ?, ?, ?, NOW())
      `;
      const sqlParams = [
        userId,
        account,
        name,
        identity,
        sex,
        phone,
        email,
        hashPassword,
      ];
      await query(sql, sqlParams, false, conn);
      const sql2 = `
    INSERT INTO daily_statistics (date, new_users)
        VALUES (CURDATE(), 1)
        ON DUPLICATE KEY UPDATE new_users = new_users + 1;
        `;
      await query(sql2, [], false, conn);
      return '注册成功';
    });
  }
  // 登录验证
  async login(account: LoginDTO['account']) {
    return transaction(async conn => {
      const sql = `
  SELECT
    u.user_id AS userId,
    u.department_id AS departmentId,
    d.name AS departmentName,
    u.account,
    u.name,
    i.item_label AS identity, 
    s.item_label AS sex, 
    u.email,
    u.phone,
    u.authentication_flag AS authenticationFlag,
    u.director_flag AS directorFlag,
    u.is_admin AS role,
    u.password AS passwordHash
FROM
    user u
LEFT JOIN
    department d ON u.department_id = d.id
LEFT JOIN
    sys_dict_item i ON u.identity = i.item_code AND i.dict_code = 'IDENTITY'
LEFT JOIN
    sys_dict_item s ON u.sex = s.item_code AND s.dict_code = 'SEX'
WHERE
  u.account = ? AND u.valid_flag = 1
`;
      const sqlParams = [account];
      const sql2 = `
    INSERT INTO daily_statistics (date, page_views)
        VALUES (CURDATE(), 1)
        ON DUPLICATE KEY UPDATE page_views = page_views + 1;
        `;
      await query(sql2, [], false, conn);
      return (await query(sql, sqlParams, true, conn))[0];
    });
  }
  //设置管理员
  @InjectClient(CachingFactory, 'redis')
  cache: MidwayCache; //redis缓存
  async setAdmin(userId: UserDTO['userId']) {
    // 更新数据库中的用户角色为管理员
    const sql = `
      UPDATE
        user
      SET
        is_admin = 1
      WHERE
        student_id = ?
    `;
    const sqlParams = [userId];
    const result = await query(sql, sqlParams);
    // 如果更新成功，更新 Redis 缓存
    if (result.affectedRows > 0) {
      await this.cache.del(`findUserId:${userId}`);
      return await this.userDao.findUserById(userId);
    }
  }
}
